import { GroupMeta } from '../declare/type';
import Shape from './shape';

export default class Group {
  protected children: (Group | Shape)[] = [];

  protected meta: GroupMeta;

  constructor (meta: GroupMeta) {
    this.meta = meta;
  }

  public addChild (child: Group | Shape) {
    this.children.push(child);
  }

  public removeChild (child: Group | Shape) {
    this.children = this.children.filter((item) => {
      if (this.isGroup(child) && this.isGroup(item)) {
        return (<Group>child).meta.label !== (<Group>item).meta.label;
      }
      if (this.isShape(child) && this.isShape(item)) {
        return (<Shape>child).getId() !== (<Shape>item).getId();
      }
      return true;
    });
  }

  public getChildren (): (Group | Shape)[] {
    return this.children;
  }

  public clearChildren () {
    this.children = [];
  }

  // eslint-disable-next-line class-methods-use-this
  public isGroup (child: Group | Shape): boolean {
    return child instanceof Group;
  }

  // eslint-disable-next-line class-methods-use-this
  public isShape (child: Group | Shape): boolean {
    return child instanceof Shape;
  }

  public draw (ctx2d: CanvasRenderingContext2D) {
    this.children.forEach((item) => {
      if (this.isShape(item)) {
        (<Shape>item).draw(ctx2d);
      }
    });
  }
}
